class Api::V1::UserScratchCardAwardsController < Api::V1::BaseController
  skip_before_action :authenticate_request!, only: [:create]

  def create
    @order = Order.find_by_id params[:order_id]
    if @order.blank?
      render json: { result: false, message: '订单不存在.' }, status: :ok and return
    end
    @user = User.find_by_id params[:user_id]
    if @order.user_id != @user.id
      render json: { result: false, message: '你没抽奖机会.' }, status: :ok and return
    end
    @scratch_card_award = ScratchCardAward.find_by_id params[:scratch_card_award_id]
    if @scratch_card_award.blank?
      render json: { result: false, message: '奖品不存在.' }, status: :ok and return
    end
    @user_scratch_card_award = UserScratchCardAward.where(
      user_id: params[:user_id],
      order_id: params[:order_id],
      scratch_card_award_id: params[:scratch_card_award_id]
    ).first
    if @user_scratch_card_award.blank?
      @user_scratch_card_award = UserScratchCardAward.new(
        user_id: params[:user_id],
        order_id: params[:order_id],
        scratch_card_award_id: params[:scratch_card_award_id]
      )
      if @user_scratch_card_award.save
        @order.send_notify("恭喜你，刮卡获得#{@scratch_card_award.name}一份。")
        render json: { result: true, message: '领取成功.' }, status: :ok and return
      else
        render json: { result: false, message: '领取失败.' }, status: :ok and return
      end
    else
      render json: { result: false, message: '已抽奖.' }, status: :ok and return
    end
  end
  
end
